package com.jiliang.common.http;

import com.jiliang.common.json.JsonDsUtil;
import com.jiliang.common.string.StringCheckDsUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @Explain
 * @CreateTime 2017/10/24 13:53
 * @Author
 */
public class HttpClientDsUtil {

    private static final Logger logger = LoggerFactory.getLogger(HttpClientDsUtil.class);

    private static final String ENCODING_UTF8 = "UTF-8";
    private static final String ENCODING_GBK = "GBK";

    public static final int INT_200 = 200;

    public static String doGet(String url, Map<String, String> param, String busName, boolean isShowLog, Map<String, String> headerMap) {
        String logBase = busName + " http get ";
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).setConnectionRequestTimeout(10000).build();
            httpGet.setConfig(requestConfig);
            if (isShowLog) {
                logger.info(logBase + "request url: " + url);
                logger.info(logBase + "request content: " + JsonDsUtil.objToJSONStr(param));
            }
            if (headerMap != null && headerMap.size() > 0) {
                Iterator<Map.Entry<String, String>> it = headerMap.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<String, String> entry = it.next();
                    httpGet.addHeader(entry.getKey(), entry.getValue());
                }
            }
            // 执行请求
            response = httpclient.execute(httpGet);
            resultString = EntityUtils.toString(response.getEntity(), ENCODING_UTF8);
            if (isShowLog) {
                logger.info(logBase + "response content: " + resultString);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(logBase + "exception");
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doGet(String url, Map<String, String> param) {
        return doGet(url, param, "", false, null);
    }

    public static String doGet(String url, Map<String, String> param, String busName) {
        return doGet(url, param, busName, true, null);
    }

    public static String doGet(String url, Map<String, String> param, Map<String, String> headerMap) {
        return doGet(url, param, "", true, headerMap);
    }

    public static String doGetNotLog(String url) {
        return doGet(url, null, "", false, null);
    }

    public static String doGet(String url) {
        return doGet(url, null, "", true, null);
    }

    public static String doPost(String url, Map<String, String> param, String busName, boolean isShowLog) {
        String logBase = busName + " http post form ";
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).setConnectionRequestTimeout(10000).build();
            httpPost.setConfig(requestConfig);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, ENCODING_UTF8);
                httpPost.setEntity(entity);
            }
            if (isShowLog) {
                logger.info(logBase + "request url: " + url);
                //logger.info(logBase + "request content: " + JsonDsUtil.objToJSONStr(param));
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), ENCODING_UTF8);
            if (isShowLog) {
                logger.info(logBase + "response content: " + resultString);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(logBase + " error");
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doPost(String url, Map<String, String> param) {
        return doPost(url, param, "", true);
    }

    public static String doPostJsonNotLog(String url, Map<String, String> param) {
        return doPost(url, param, "", false);
    }

    public static String doPost(String url) {
        return doPost(url, null);
    }

    public static String doPostJson(String url, String json, String busName) {
        return doPostJson(url, json, busName, true);
    }

    public static String doPostJsonNotLog(String url, String json) {
        return doPostJson(url, json, "", false);
    }

    public static String doPostJson(String url, String json) {
        return doPostJson(url, json, "", true);
    }

    public static String doPostJson(String url, String json, String busName, Boolean isShowLog) {
        // 创建Httpclient对象
        String logBase = busName + "http post json ";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).setConnectionRequestTimeout(10000).build();
            httpPost.setConfig(requestConfig);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            if (isShowLog) {
                logger.info(logBase + "request url: " + url);
                logger.info(logBase + "request content: " + json);
            }
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), ENCODING_UTF8);
            if (isShowLog) {
                logger.info(logBase + "response content: " + resultString);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(logBase + " error");
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return resultString;
    }

    /**
     * 发送post请求--队列
     *
     * @return
     */
    public static String post(String url, List<BasicNameValuePair> params) throws IOException {
        String result = null;
        //创建默认的httpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建httppost
        HttpPost httpPost = new HttpPost(url);
        try {
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(params, "GBK");
            httpPost.setEntity(urlEncodedFormEntity);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).setConnectionRequestTimeout(10000).build();
            httpPost.setConfig(requestConfig);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, "GBK");
        } finally {
            //关闭连接,释放资源
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 带请求头的post请求
     *
     * @param url
     * @param json
     * @param encoding
     * @param headerMap
     * @return java.lang.String
     * @author
     * @date 14:45 2018/11/8
     **/
    public final static String postJson(String url, String json, String encoding, Map<String, String> headerMap) {
        try {
            if (StringCheckDsUtil.isBlank(url)) {
                throw new IllegalAccessException("请求地址为空");
            }
            //创建默认的httpClient实例
            CloseableHttpClient httpClient = HttpClients.createDefault();
            // POST方法
            HttpPost postMethoed = new HttpPost(url);
            postMethoed.setHeader("Content-type", "application/json");
            if (headerMap != null && headerMap.size() > 0) {
                Iterator<Map.Entry<String, String>> it = headerMap.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<String, String> entry = it.next();
                    postMethoed.setHeader(entry.getKey(), entry.getValue());
                }
            }
            StringEntity strEntity = new StringEntity(json, encoding);
            // 设置请求参数
            postMethoed.setEntity(strEntity);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).setConnectionRequestTimeout(10000).build();
            postMethoed.setConfig(requestConfig);
            CloseableHttpResponse response = null;
            HttpEntity entity = null;
            try {
                response = httpClient.execute(postMethoed);
                if (null == response) {
                    return null;
                }
                entity = response.getEntity();
                if (null == entity) {
                    return null;
                }
                String result = EntityUtils.toString(entity, encoding);
                if (StringCheckDsUtil.isBlank(result)) {
                    return null;
                }
                return result;
            } catch (ClientProtocolException e) {
                logger.error("错误信息 : " + e.getMessage(), e);
                throw e;
            } catch (IOException e) {
                if (e instanceof org.apache.http.conn.ConnectTimeoutException) {
                    throw new org.apache.http.conn.ConnectTimeoutException("请求连接超时  请求参数 url : " + url
                            + " json : " + json);
                } else if (e instanceof SocketTimeoutException) {
                    throw new SocketTimeoutException("服务器响应超时 请求参数 url : " + url
                            + " json : " + json);
                } else {
                    throw e;
                }
            } catch (Exception e) {
                throw e;
            } finally {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    logger.error("关闭流异常 请求参数 url : " + url + " json : " + json);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * xml post请求
     *
     * @param url
     * @param xml
     * @param encoding
     * @return java.lang.String
     * @author
     * @date
     **/
    public static String postXml(String url, String xml, String encoding) throws IOException {
        logger.info("请求路径：" + url);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        //设置请求和传输超时
        RequestConfig config = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).setConnectionRequestTimeout(10000).build();
        StringEntity strEntity = new StringEntity(xml, encoding);
        post.setEntity(strEntity);
        post.setConfig(config);
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(post);
            HttpEntity entity = response.getEntity();
            if (null == entity) {
                return null;
            }
            String result = EntityUtils.toString(entity, ENCODING_UTF8);
            return result;
        } catch (ClientProtocolException e) {
            System.out.println("httpClient异常：" + e.getMessage());
        } catch (IOException e) {
            System.out.println("httpClient异常：" + e.getMessage());
        } finally {
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    System.out.println("httpClient异常：" + e.getMessage());
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    System.out.println("httpClient异常：" + e.getMessage());
                }
            }
        }
        return null;
    }

    public static String postMap(String url, Map<String,String> headerMap, Map<String, String> contentMap) {
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        List<NameValuePair> content = new ArrayList<NameValuePair>();
        //将content生成entity
        Iterator iterator = contentMap.entrySet().iterator();
        while(iterator.hasNext()){
            Map.Entry<String,String> elem = (Map.Entry<String, String>) iterator.next();
            content.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
        }
        CloseableHttpResponse response = null;
        try {
            //循环增加header
            Iterator headerIterator = headerMap.entrySet().iterator();
            while(headerIterator.hasNext()){
                Map.Entry<String,String> elem = (Map.Entry<String, String>) headerIterator.next();
                post.addHeader(elem.getKey(),elem.getValue());
            }
            if(content.size() > 0){
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(content,ENCODING_UTF8);
                post.setEntity(entity);
            }
            //发送请求并接收返回数据
            response = httpClient.execute(post);
            if(response != null && response.getStatusLine().getStatusCode() == 200)
            {
                //获取response的body部分
                HttpEntity entity = response.getEntity();
                //读取reponse的body部分并转化成字符串
                result = EntityUtils.toString(entity);
            }
            return result;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                httpClient.close();
                if(response != null)
                {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }

    public static String httpRequest(String requestUrl, String requestJson, Map<String,String> headers, HttpMethod httpMethod, String encode) {
        CloseableHttpClient httpClient = null;
        try {
            httpClient = HttpClients.createDefault();
            HttpResponse response;

            if (null == httpMethod) {
                throw new RuntimeException("Http Method should be Get, Post, Put or Delete.");
            }
            if (HttpMethod.GET == httpMethod) {
                HttpGet httpGet = new HttpGet(requestUrl);
                response = httpClient.execute(httpGet);
            } else {
                HttpEntityEnclosingRequestBase requestBase = null;
                switch (httpMethod) {
                    case POST:
                        requestBase = new HttpPost(requestUrl);
                        break;
                    case PUT:
                        requestBase = new HttpPut(requestUrl);
                        break;
//                    case DELETE:
//                        requestBase = new HttpDeleteWithBody(requestUrl);
//                        break;
                }
                if (headers != null && headers.size() > 0) {
                    for (Map.Entry<String, String> entry : headers.entrySet()) {
                        requestBase.setHeader(entry.getKey(),entry.getValue());
                    }
                }
                if (StringUtils.isNotBlank(requestJson)) {
                    StringEntity requestEntity = new StringEntity(requestJson, ContentType.APPLICATION_JSON);
                    if (requestBase != null) {
                        requestBase.setEntity(requestEntity);
                    }
                }
                response = httpClient.execute(requestBase);
            }

            HttpEntity httpEntity = response.getEntity();
            return EntityUtils.toString(httpEntity, encode);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] arg) {
        String url = "https://products.t.nxin.com/api/good";
        String s = HttpClientDsUtil.httpRequest(url, null, null, HttpMethod.PUT, HttpClientDsUtil.ENCODING_UTF8);
        System.out.println(s);
    }
}
